const User = require("../mysql/user"); // 引入 User 模型
const config = require("../config");
const jwt = require("jsonwebtoken"); // 引入 jsonwebtoken
const AgentList = require("../mysql/Invoice");
const moment = require("moment");
const xlsx = require("xlsx");
const FileTypes = require("../constants/filetype.json");
const { fileUpload } = require("../service/adminFile");
const FileUpload = require("../mysql/FileUpload");

exports.createUser = async (ctx) => {
  try {
    const { username, password } = ctx.request.body;

    // 检查用户是否已存在
    const existingUser = await User.findOne({ where: { username } });
    if (existingUser) {
      ctx.status = 409; // 冲突状态码
      ctx.body = { code: 409, message: "用户已存在" };
      return;
    }

    // 创建新用户
    const newUser = await User.create({
      username,
      password,
    });

    // 生成 JWT 令牌
    const token = jwt.sign({ userId: newUser.id }, config.jwtSecret, {
      expiresIn: "1d",
    });

    ctx.status = 200; // 创建成功状态码
    ctx.body = {
      code: 200,
      message: "用户创建成功",
      token: `Bearer ${token}`,
      user: {
        id: newUser.id,
        username: newUser.username,
      },
    };
  } catch (err) {
    console.error("创建用户错误：", err);
    ctx.status = 500;
    ctx.body = { code: 500, message: err.message || "服务器错误" };
  }
};
exports.loginUser = async (ctx) => {
  try {
    const { username, password } = ctx.request.body;
    const user = await User.findOne({ where: { username, password } });
    if (!user) {
      ctx.status = 401;
      ctx.body = { code: 401, message: "用户名或密码错误" };
      return;
    }
    if (user.password != password) {
      ctx.status = 40;
      ctx.body = { code: 400, message: "用户名或密码错误" };
      return;
    }
    const token = jwt.sign({ userId: user.id }, config.jwtSecret, {
      expiresIn: "1d",
    });
    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: "登录成功",
      token: `Bearer ${token}`,
      user: {
        id: user.id,
        username: user.username,
      },
    };
  } catch (err) {
    console.error("登录用户错误：", err);
    ctx.status = 500;
    ctx.body = { code: 500, message: err.message || "服务器错误" };
  }
};
exports.addAgentList = async (ctx) => {
  const {
    totalInvoiceAmount,
    totalAmount = "",
    payerName,
    infos,
  } = ctx.request.body;
  ctx.assert(payerName, 400, "参数错误,payerName");
  ctx.assert(totalInvoiceAmount, 400, "参数错误,userId");
  ctx.assert(infos && infos.length >= 1, 400, "参数错误,infos");
  ctx.assert(totalAmount, 400, "参数错误,totalAmount");
  const uuid = `FS${moment().format("YYYYMMDDHHmmss")}`;
  try {
    await AgentList.create({
      payerName,
      infos,
      uuid,
      totalInvoiceAmount,
      totalAmount,
    });
    ctx.body = { code: 200 };
  } catch (err) {
    console.error("添加代理错误：", err);
    ctx.status = 500;
    ctx.body = { code: 500, message: err.message || "服务器错误" };
  }
};
exports.invoiceDownload = async (ctx) => {
  const { id } = ctx.request.body;
  console.log(id, "id");

  let data = await Invoice.findOne({
    where: { id },
  });
  console.log(data, "data");

  // 创建一个工作簿
  const workbook = xlsx.utils.book_new();
  // 将数据转换为工作表
  const worksheet = xlsx.utils.json_to_sheet([data]);
  // 将工作表添加到工作簿
  xlsx.utils.book_append_sheet(workbook, worksheet, "Invoice Data");
  // 将工作簿转换为二进制字符串
  const excelBuffer = xlsx.write(workbook, {
    type: "buffer",
    bookType: "xlsx",
  });
  // 设置响应头为Excel文件
  ctx.set(
    "Content-Type",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  );
  ctx.set("Content-Disposition", `attachment; filename=invoice_${id}.xlsx`);
  // 发送Excel文件
  ctx.body = excelBuffer;
};
exports.getAllInvoices = async (ctx) => {
  try {
    const invoices = await AgentList.findAll({
      // 可以添加其他查询选项，例如排序等
    });

    // 格式化日期
    const formattedInvoices = invoices.map((invoice) => {
      return {
        ...invoice.get({ plain: true }),
        createdAt: invoice.get("createdAt").toLocaleDateString("zh-CN"),
      };
    });

    console.log(formattedInvoices, "Formatted Invoices");

    ctx.status = 200;
    ctx.body = {
      code: 200,
      data: formattedInvoices,
    };
  } catch (err) {
    console.error("获取所有发票错误：", err);
    ctx.status = 500;
    ctx.body = { code: 500, message: err.message || "服务器错误" };
  }
};
exports.upload = async (ctx) => {
  try {
    const { fileType } = ctx.request.body;
    console.log(fileType, "filetype");

    ctx.assert(
      fileType && FileTypes.includes(fileType),
      400,
      "fileType is invalid"
    );

    // const tenant = await getTennatByUserId(ctx.state.userId);
    // ctx.assert(tenant, 400, "tenant is invalid");
    ctx.assert(ctx.request.is("multipart/form-data"), 400, "format is invalid");

    const file = ctx.request.files.file;
    const result = await fileUpload(file, fileType);
    console.log(result, "----");

    ctx.assert(
      result.success && result?.data,
      400,
      result.message || "upload failed"
    );

    await FileUpload.create({
      bisonId: result.data,
      fileType,
      originalFilename: file.originalFilename,
      filename: file.newFilename,
    });

    ctx.body = {
      code: 200,
      data: {
        originalFilename: file.originalFilename,
        filename: file.newFilename,
        bison: result.data,
      },
    };
  } catch (err) {
    ctx.status = 500;
    ctx.body = { code: 500, message: err.message };
  }
};
